package com.riddle.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import com.riddle.model.Menu;
import com.riddle.model.Role;
import com.riddle.model.User;
import com.riddle.util.StringUtil;
import com.riddle.vmodel.ValuePair;

@Repository
@Scope("prototype")  
public class UserDao  extends BaseDao<User> {

	public User query(Long id){
		return super.query(id, "selectUserById");
	}
	
	public List<User> queryModelByPage(Integer page, Integer rows, String query){
		return super.queryModelByPage(page, rows, query, "selectUserForQuery");
	}
	
	public void insert(User model) {
		super.insert(model, "insertUser");
	}
	
	public void update(User model) {
		super.update(model, "updatetUser");
	}
	
	public void delete(Long id) {
		super.delete(id, "deleteUser");
	}
	
	public User getUserWithRole(Long id){
		return super.query(id, "selectUserWithRole");
	}
	
	public void deleteUserRole(Long id) {
		super.delete(id, "deleteUserRole");
	}
	
	public void saveUserRole(List<ValuePair<Long, String>> list) {
		try(SqlSession session = openSession()){
			session.insert("insertUserRole", list);
		}
	}
	
	public List<User> queryParent(){
		throw new UnsupportedOperationException();
	}
	
	public boolean check(String name, String password) {
		Map param = new HashMap<String, String>();
		param.put("name", name);
		param.put("password", password);
		List<User> users = super.query("getUser", param);
		if(users != null && users.size() > 0) {
			return users.get(0).getName().equals(name) && users.get(0).getPassword().equals(password);
		}
		return false;
	}
	
	public User getUser(String name) {
		Map param = new HashMap<String, String>();
		param.put("name", name);
		List<User> users = super.query("getUser", param);
		if(users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}
	
	public User getUserWithRoleAndPermission(String name) {
		Map param = new HashMap<String, String>();
		param.put("name", name);
		List<User> users = super.query("getUserWithRoleAndPermission", param);
		if(users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}
}